<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Dart File》 - 飞雪无情的博客</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Java、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Dart File》" />
<meta property="og:description" content="
本文主要简单了解 Dart File 类的用法。
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.flysnow.org/posts/flutter/Dart-File/" />
<meta property="article:published_time" content="2021-06-24T21:41:33+08:00" />
<meta property="article:modified_time" content="2021-06-24T21:41:33+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Dart File》"/>
<meta name="twitter:description" content="
本文主要简单了解 Dart File 类的用法。
"/>
<meta name="application-name" content="飞雪无情的博客">
<meta name="apple-mobile-web-app-title" content="飞雪无情的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://www.flysnow.org/posts/flutter/Dart-File/" /><link rel="prev" href="https://www.flysnow.org/posts/flutter/Dart-VM-Service%E7%AE%80%E4%BB%8B/" /><link rel="next" href="https://www.flysnow.org/posts/flutter/Dar-JIT%E5%92%8CAOT/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Dart File》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/www.flysnow.org\/posts\/flutter\/Dart-File\/"
        },"genre": "posts","keywords": "flutter","wordcount":  952 ,
        "url": "https:\/\/www.flysnow.org\/posts\/flutter\/Dart-File\/","datePublished": "2021-06-24T21:41:33+08:00","dateModified": "2021-06-24T21:41:33+08:00","publisher": {
            "@type": "Organization",
            "name": "飞雪无情"},"author": {
                "@type": "Person",
                "name": "飞雪无情"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">飞雪无情的博客</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/tools/">工具</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/archives/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Dart File》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>飞雪无情</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-06-24">2021-06-24</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;952 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;2 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents"></nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要简单了解 Dart File 类的用法。</p>
</blockquote>
<h1 id="dart-file-类">Dart File 类</h1>
<p>原文见<a href="https://api.dartlang.org/stable/2.4.0/dart-io/File-class.html" target="_blank" rel="noopener noreffer">这里</a></p>
<p>File 表示文件系统中某个文件的引用。</p>
<p>File 实例是个对象，它持有 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/path.html" target="_blank" rel="noopener noreffer">path</a> 并对其进行操作。可以使用 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity/parent.html" target="_blank" rel="noopener noreffer">parent</a> getter 获取父目录，<code>parent</code> 属性继承自 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity-class.html" target="_blank" rel="noopener noreffer">FileSystemEntity</a>。</p>
<p>使用 pathname 创建新的 File 对象来访问文件系统上的文件。</p>
<pre><code>var myFile = new File('file.txt');
</code></pre><p>File 类包含操作文件及其内容的方法。使用这些方法，可以打开和关闭文件，读写文件，创建和删除文件，以及检查文件是否存在。</p>
<p>读写文件时，可以使用 stream (通过 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/openRead.html" target="_blank" rel="noopener noreffer">openRead</a>)，随机访问操作 (通过 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/open.html" target="_blank" rel="noopener noreffer">open</a>)，或者类似 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/readAsString.html" target="_blank" rel="noopener noreffer">readAsString</a> 这样的便捷方法。</p>
<p>File 类中的方法大部分都有同步和异步两种形式，比如 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/readAsString.html" target="_blank" rel="noopener noreffer">readAsString</a> 和 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/readAsStringSync.html" target="_blank" rel="noopener noreffer">readAsStringSync</a>。除非有特别的理由，通常应当使用异步方法以避免阻塞程序。</p>
<p>如果构造 File 对象的 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/path.html" target="_blank" rel="noopener noreffer">path</a> 是一个符号链接，而非文件，则 File 类的方法会操作链接指向的最终目标文件。不过，<a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity/delete.html" target="_blank" rel="noopener noreffer">delete</a> 和 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity/deleteSync.html" target="_blank" rel="noopener noreffer">deleteSync</a> 方法除外，这两个方法是对符号链接进行操作。</p>
<h1 id="读文件">读文件</h1>
<p>下面示例代码使用异步的 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/readAsString.html" target="_blank" rel="noopener noreffer">readAsString</a> 方法读取文件，它将整个文件内容视为一个字符串：</p>
<pre><code>import 'dart:async';
import 'dart:io';

void main() {
  new File('file.txt').readAsString().then((String contents) {
    print(contents);
  });
}
</code></pre><p>更灵活更有用的方法是使用 <a href="https://api.dartlang.org/stable/2.4.0/dart-async/Stream-class.html" target="_blank" rel="noopener noreffer">Stream</a> 方式读文件。调用 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/openRead.html" target="_blank" rel="noopener noreffer">openRead</a> 方法打开文件，该方法返回 stream，这个 stream 以字节块的方式返回文件数据。可以监听 stream 来获取数据并进行必要的处理。可以继续使用不同的 transformer 操作数据来得到想要的数据格式。</p>
<p>可以使用 stream 方式来读取大文件，并提供 transformer 来操作数据。</p>
<pre><code>import 'dart:io';
import 'dart:convert';
import 'dart:async';

main() {
  final file = new File('file.txt');
  Stream&lt;List&lt;int&gt;&gt; inputStream = file.openRead();

  inputStream
    .transform(utf8.decoder)       // Decode bytes to UTF-8.
    .transform(new LineSplitter()) // Convert stream to individual lines.
    .listen((String line) {        // Process results.
        print('$line: ${line.length} bytes');
      },
      onDone: () { print('File is now closed.'); },
      onError: (e) { print(e.toString()); });
}
</code></pre><h1 id="写文件">写文件</h1>
<p>使用 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/writeAsString.html" target="_blank" rel="noopener noreffer">writeAsString</a> 方法写文件。</p>
<pre><code>import 'dart:io';

void main() {
  final filename = 'file.txt';
  new File(filename).writeAsString('some content')
    .then((File file) {
      // Do something with the file.
    });
}
</code></pre><p>也可以使用 <a href="https://api.dartlang.org/stable/2.4.0/dart-async/Stream-class.html" target="_blank" rel="noopener noreffer">Stream</a> 来写入文件。调用 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/openWrite.html" target="_blank" rel="noopener noreffer">openWrite</a> 方法打开文件，返回结果是 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/IOSink-class.html" target="_blank" rel="noopener noreffer">IOSink</a>，可以向 IOSink 写入数据。记得操作完成后调用 <a href="https://api.dartlang.org/stable/2.4.0/dart-io/IOSink/close.html" target="_blank" rel="noopener noreffer">IOSink.close</a> 关闭 sink。</p>
<pre><code>import 'dart:io';

void main() {
  var file = new File('file.txt');
  var sink = file.openWrite();
  sink.write('FILE ACCESSED ${new DateTime.now()}\n');

  // Close the IOSink to free system resources.
  sink.close();
}
</code></pre><h1 id="使用-future">使用 Future</h1>
<p>为避免意外阻塞程序，File 类的一些方法使用 <a href="https://api.dartlang.org/stable/2.4.0/dart-async/Future-class.html" target="_blank" rel="noopener noreffer">Future</a> 作为返回值。比如，<a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/length.html" target="_blank" rel="noopener noreffer">length</a> 方法用于获取文件长度，返回的是 Future。调用 <code>then</code> 方法注册回调函数，获取到文件长度后会回调这个函数。</p>
<pre><code>import 'dart:io';

main() {
  final file = new File('file.txt');

  file.length().then((len) {
    print(len);
  });
}
</code></pre><p>除了 <code>length()</code> 外，其他几个方法也返回 Future，包括：<a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity/exists.html" target="_blank" rel="noopener noreffer">exists</a>，<a href="https://api.dartlang.org/stable/2.4.0/dart-io/File/lastModified.html" target="_blank" rel="noopener noreffer">lastModified</a>，<a href="https://api.dartlang.org/stable/2.4.0/dart-io/FileSystemEntity/stat.html" target="_blank" rel="noopener noreffer">stat</a> 等等。</p>
<h1 id="其他资源">其他资源</h1>
<ul>
<li><a href="https://www.dartlang.org/dart-by-example/#files-directories-and-symlinks" target="_blank" rel="noopener noreffer">Dart by Example</a> provides additional task-oriented code samples that show how to use various API from the Directory class and the related File class.</li>
<li>I<a href="https://www.dartlang.org/docs/dart-up-and-running/ch03.html#dartio---io-for-command-line-apps" target="_blank" rel="noopener noreffer">I/O for Command-Line Apps</a> a section from A Tour of the Dart Libraries covers files and directories.</li>
<li><a href="https://www.dartlang.org/docs/tutorials/cmdline/" target="_blank" rel="noopener noreffer">Write Command-Line Apps</a>, a tutorial about writing command-line apps, includes information about files and directories.</li>
</ul></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-06-24</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/Dart-VM-Service%E7%AE%80%E4%BB%8B/" class="prev" rel="prev" title="《Dart VM Service简介》"><i class="fas fa-angle-left fa-fw"></i>《Dart VM Service简介》</a>
            <a href="/posts/flutter/Dar-JIT%E5%92%8CAOT/" class="next" rel="next" title="《Dar JIT和AOT》">《Dar JIT和AOT》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">飞雪无情</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
